import router from './router/'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import pinia from '@/stores/index'
import { useUserStore } from '@/stores/user'
const UserStore = useUserStore(pinia)
router.beforeEach(async (to: any, from: any, next: any) => {
  const token = UserStore.token
  const username = UserStore.username
  if (token) {
    if (to.path == '/login') {
      next({
        path: '/'
      })
    } else {
      if (username) {
        next()
      } else {
        try {
          await UserStore.getUserInfo()
          next({ ...to })
        } catch (error) {
          await UserStore.clearInfo()
          next({ path: '/login' })
        }
      }
    }
  } else {
    if (to.path == '/login') {
      next()
    } else {
      next({
        path: '/login',
        query: {
          redirect: to.path
        }
      })
    }
  }
  NProgress.start()
})
router.afterEach(() => {
  NProgress.done()
})
